package co.fitstart.admin.web.controller.finance;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.support.Page;
import com.demo2do.core.utils.CollectionUtils;
import com.demo2do.core.web.utils.WebUtils;

import co.fitstart.admin.entity.security.Login;
import co.fitstart.admin.service.DataService;
import co.fitstart.admin.service.OrderService;
import co.fitstart.admin.service.PrincipalService;
import co.fitstart.admin.web.interceptor.MenuSetting;
import co.fitstart.admin.web.resolver.Secure;
import co.fitstart.admin.web.view.ExcelTemplateView;
import co.fitstart.entity.finance.ExchangeRate;
import co.fitstart.entity.finance.PaidType;
import co.fitstart.entity.finance.Receipt;
import co.fitstart.entity.finance.ReceiptType;
import co.fitstart.entity.order.Order;
import co.fitstart.entity.order.PaymentStatus;
import co.fitstart.entity.principal.Principal;

@Controller
@RequestMapping("/receipts")
@MenuSetting("menu-finance")
public class ReceiptController {
    
    @Autowired
    private OrderService orderService;
    
    @Autowired
    private PrincipalService principalService;
    
    @Autowired
    @Qualifier("dataService")
    private DataService<ExchangeRate> exchangeRateService;
    
    /**
     * 
     * @param page
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET, params = "type=sale")
    @MenuSetting("submenu-{paidType}-management")
    public ModelAndView listSale(@RequestParam(name = "export", required = false, defaultValue = "false") boolean export,
                                 @RequestParam("paidType") String paidType,
                                 Page page,
                                 HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("finance/sale-receipt-list");
        
        List<Receipt> receipts = orderService.listReceipt( PaidType.aliasOf(paidType), export, page);
        modelAndView.addObject("receipts", receipts);
        
        modelAndView.addObject("page", page);
        modelAndView.addObject("export", export);
        modelAndView.addObject("paidType", paidType);
        
        modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page"));
        
        return modelAndView;
        
    }
    
    /**
     * 
     * @param export
     * @param page
     * @param request
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET, params = "type=refund")
    @MenuSetting("submenu-refund-management")
    public ModelAndView listRefund(@RequestParam(name = "export", required = false, defaultValue = "false") boolean export,
                                   Page page,
                                   HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("finance/refund-receipt-list");
        
        List<Order> orders = orderService.list(export, new PaymentStatus[]{PaymentStatus.REFUNDED, PaymentStatus.SYSTEMREFUNDED}, page);
        modelAndView.addObject("orders", orders);
        
        modelAndView.addObject("page", page);
        modelAndView.addObject("export", export);
        
        modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page"));
        
        return modelAndView;
        
    }
    
    /**
     * 
     * @return
     */
    @RequestMapping(value = "/export-view", method = RequestMethod.GET)
    public ModelAndView export(@RequestParam("type") String type,
                               @RequestParam(name = "paidType", required = false) String paidType) {
        ModelAndView modelAndView = new ModelAndView("finance/receipt-export");
        
        modelAndView.addObject("type", type);
        modelAndView.addObject("paidType", paidType);
        
        return modelAndView;
        
    }
    
    /**
     * 
     * @param login
     * @return
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/export", method = RequestMethod.GET, params = "type=sale")
    public ModelAndView onSaleExport(@Secure Login login, @RequestParam("paidType") String paidType) {
        ModelAndView modelAndView = new ModelAndView(new ExcelTemplateView("sale-receipt-record.xls"));
        
        List<Receipt> receipts = orderService.listReceipt(PaidType.aliasOf(paidType), false);
        modelAndView.addObject("type", "48");
        modelAndView.addObject("receipts", receipts);
        
        Map<Long, Principal> managers = principalService.listSiteManager();
        modelAndView.addObject("managers", managers);
        
        List<ExchangeRate> exchangeRates = exchangeRateService.listAll(ExchangeRate.class);
        modelAndView.addObject("exchangeRate", exchangeRates.isEmpty() ? null : exchangeRates.get(0));
        
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
        modelAndView.addObject("fmt", format);
        
        
        // update student's exportArchives
        if(!receipts.isEmpty()) {
            List<Long> receiptIds = CollectionUtils.extractPropertyList(receipts, "id");
            ReceiptType receiptType = StringUtils.equals(paidType, "deposit") ? ReceiptType.DEPOSIT : ReceiptType.BALANCE;
            orderService.exportSaleReceipt(receiptIds, receiptType, login.getId());
        }
        
        return modelAndView;
    }
    
    /**
     * 
     * @param login
     * @return
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/export", method = RequestMethod.GET, params = "type=refund")
    public ModelAndView onRefundExport(@Secure Login login) {
        ModelAndView modelAndView = new ModelAndView(new ExcelTemplateView("refund-receipt-record.xls"));
        
        // list all unexport student
        List<Order> orders  = orderService.list(new PaymentStatus[]{PaymentStatus.REFUNDED, PaymentStatus.SYSTEMREFUNDED});
        modelAndView.addObject("type", "49");
        modelAndView.addObject("orders", orders);
        
        Map<Long, Principal> managers = principalService.listSiteManager();
        modelAndView.addObject("managers", managers);
        
        List<ExchangeRate> exchangeRates = exchangeRateService.listAll(ExchangeRate.class);
        modelAndView.addObject("exchangeRate", exchangeRates.isEmpty() ? null : exchangeRates.get(0));
        
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
        modelAndView.addObject("fmt", format);
        
        
        // update student's exportArchives
        if(!orders.isEmpty()) {
            List<Long> orderIds = CollectionUtils.extractPropertyList(orders, "id");
            orderService.exportReceipt(orderIds, ReceiptType.REFUND, login.getId());
        }
        
        return modelAndView;
    }

}
